<?php
/**
 * Created by PhpStorm.
 * User: 颖inv
 * Date: 2016/11/2
 * Time: 18:23
 */
header('content-type:text/html;charset=utf-8');
echo '<h2>接收到新用户注册！</h2>';
echo '<p>用户名:'.$_POST['username'].'</p>';
echo '<p>密码：'.$_POST['password'].'</p>';
echo '<p>邮箱：'.$_POST['email'].'</p>';
echo '<p>IP地址：'.$_SERVER['REMOTE_ADDR'].'</p>';
echo '<p>浏览器环境：'.$_SERVER['HTTP_USER_AGENT'].'</p>';
echo '<p>请求来源：'.$_SERVER['HTTP_REFERER'].'</p>';
//当没有表单提交时退出程序
if (empty($_POST)){
    die('没有表单提交，程序退出');
}
//判断表单中各字段是否都已填写
$check_fields = array('username','password','email');
foreach($check_fields as $v){
    if(empty($_POST[$v])){
        die('错误：'.$v.'字段不能为空！');
    }
}

$username=$_POST['username'];
$password=$_POST['password'];
$email=$_POST['email'];

$link=mysqli_connect('localhost','root','') or die('数据库连接失败！');
mysqli_query($link,'set names utf8');
mysqli_query($link,'use itcast') or die('itcast数据库不存在！');

//防止SQL注入
$username=mysqli_real_escape_string($link,$username);
$email=mysqli_real_escape_string($link,$email);

//判断用户名是否已经存在
$sql="select `id` from `user` where `username`='$username'";
$rst=mysqli_query($link,$sql);
if (mysqli_fetch_row($rst)){
    die('用户名已经存在，请换个用户名。');
}

//使用MD5增强密码安全性
$password=md5($password);
$sql="insert into `user`(`username`,`password`,`email`) values('$username','$password','$email')";
$rst=mysqli_query($link,$sql);

echo "SQL语句：$sql<br>";
if ($rst){
    echo '执行成功';
}

//引入表单验证函数库
require 'check_form.lib.php';

$data=array(
    'username'=>'小明',
    'password'=>'123456',
    'email'=>'xiaoming@123.com',
);

$validate=array(
    //表单字段名=>验证函数名
    'username'=>'checkUsername',
    'password'=>'checkPassword',
    'email'=>'checkEmail',
);
$error=array();
foreach ($validate as $k=>$v){
    $result=$v($data[$k]);
    if ($result !==true){
        $error[]=$result;
    }
}
if (empty($error)){
    //表单验证成功
}else{
    //表单验证失败，显示错误信息
    
}

//生成密码盐
$salt=md5(uniqid(microtime()));
//提升密码安全
$password=md5($salt,md5($password));
//拼接SQL语句
$sql="insert into `user`(`username`,`password`,`salt`,`email`)values('$username','$password','$salt','$email')";
//执行SQL语句
$rst=mysqli_query($link,$sql);


?>

